package com.cmy.service.impl;

import com.cmy.bean.DdlHistory;
import com.cmy.service.DdlHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

/**
 * @author : Cmy
 * @date : 2024-09-13 18:21
 */
@Service
public class DdlHistoryServiceImpl implements DdlHistoryService {

    private List<DdlHistory> ddlhistoryCache = Collections.emptyList();


    @Override
    public int save(DdlHistory ddlHistory, JdbcTemplate jdbcTemplate) {
        String sql = "INSERT INTO ddl_history (id, version, description, script, checksum, installed_by, installed_on, execution_time, success) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        int update = jdbcTemplate.update(sql,
                ddlHistory.getId(),
                ddlHistory.getVersion(),
                ddlHistory.getDescription(),
                ddlHistory.getScript(),
                ddlHistory.getChecksum(),
                ddlHistory.getInstalledBy(),
                ddlHistory.getInstalledOn(),
                ddlHistory.getExecutionTime(),
                ddlHistory.getSuccess());
        return update;
    }

    @Override
    public List<DdlHistory> cacheList(JdbcTemplate jdbcTemplate) {
        if (ddlhistoryCache.isEmpty()) {
            String sql = "SELECT * FROM ddl_history order by id";
            ddlhistoryCache = jdbcTemplate.query(sql, new DdlHistoryRowMapper());
        }
        return ddlhistoryCache;

    }

    private class DdlHistoryRowMapper implements RowMapper<DdlHistory> {
        @Override
        public DdlHistory mapRow(ResultSet rs, int rowNum) throws SQLException {
            DdlHistory history = new DdlHistory();
            history.setId(rs.getLong("id"));
            history.setVersion(rs.getString("version"));
            history.setDescription(rs.getString("description"));
            history.setScript(rs.getString("script"));
            history.setChecksum(rs.getLong("checksum"));
            history.setInstalledBy(rs.getString("installed_by"));
            history.setInstalledOn(rs.getTimestamp("installed_on").toLocalDateTime());
            history.setExecutionTime(rs.getLong("execution_time"));
            history.setSuccess(rs.getBoolean("success"));
            return history;
        }
    }


}

    